package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.article.entity.ApAuthor;
import com.usian.article.mapper.ApAuthorMapper;
import com.usian.article.service.IApAuthorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.util.BeanHelper;
import com.usian.model.article.dtos.AuthorDto;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * APP文章作者信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-05
 */
@Service
public class ApAuthorServiceImpl extends ServiceImpl<ApAuthorMapper, ApAuthor> implements IApAuthorService {
    /**
     * 根据id查询用户是否存在
     * @param apUserId
     * @return
     */
    @Override
    public AuthorDto findByUserId(Integer apUserId) {
        LambdaQueryWrapper<ApAuthor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApAuthor::getUserId,apUserId);
        ApAuthor author = getOne(lambdaQueryWrapper);
        //如果author存在返回
        if (!StringUtils.isEmpty(author)){
            AuthorDto authorDto = BeanHelper.copyProperties(author, AuthorDto.class);
            return authorDto;
        }
        //如果不存在返回空
        return null;
    }

    /**
     * 创建作者
     * @param authorDto
     * @return
     */
    @Override
    public Integer saveAuthor(AuthorDto authorDto) {
        //如果==null
        if (StringUtils.isEmpty(authorDto)){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"参数不正确");
        }
        //不为空判断是否存在
        AuthorDto authorDto1 = findByUserId(authorDto.getUserId());
        if (!StringUtils.isEmpty(authorDto1)){
            return authorDto1.getId();
        }
        //创建作者
        ApAuthor apAuthor = BeanHelper.copyProperties(authorDto, ApAuthor.class);
        apAuthor.setCreatedTime(new Date());
        apAuthor.setType(2);
        boolean b = save(apAuthor);
        if (!b){
            throw  new LeadException(AppHttpCodeEnum.SERVER_ERROR,"创建作者失败");
        }
        return apAuthor.getId();
    }

    @Override
    public ApAuthor findById(Integer id) {
        if (id==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE,"参数不存在");
        }
        LambdaQueryWrapper<ApAuthor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApAuthor::getId,id);
        ApAuthor author = getOne(lambdaQueryWrapper);
        return author;
    }
}
